﻿using AntdUI;
using JinYuan.ControlLib;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Windows.Forms;


namespace Language
{
    /// <summary>
    /// 全局语言管理器 UpperComputerSystem.Language.MsgResources
    /// </summary>
    public static class LanguageManager
    {
        public static ResourceManager rm = new ResourceManager("Language.Languages", typeof(LanguageManager).Assembly);
        private static CultureInfo currentCulture = CultureInfo.CurrentUICulture;
        public static event EventHandler LanguageChanged;
        public static string LanguageCode = "zh";//默认中文

        private static Dictionary<string, string> translationCache = new Dictionary<string, string>();

        static LanguageManager()
        {
            // 在静态构造函数中加载保存的语言设置
            LoadSavedLanguage();
        }

        public static void ChangeLanguage(string languageCode)
        {
            LanguageCode = languageCode;
            currentCulture = new CultureInfo(languageCode);
            Thread.CurrentThread.CurrentUICulture = currentCulture;
            translationCache.Clear();
            SaveLanguagePreference(languageCode);
            LanguageChanged?.Invoke(null, EventArgs.Empty);

        }

        public static string GetString(string key)
        {
            if (translationCache.TryGetValue(key, out string cachedResult))
            {
                return cachedResult;
            }

            string result = rm.GetString(key, currentCulture);
            if (result != null)
            {
                translationCache[key] = result;
            }
            return result ?? key;
        }


        // 新增：GetLocalizedString 方法，支持带参数的本地化字符串
        public static string GetLocalizedString(string key, params object[] args)
        {
            string value = GetString(key);
            return args.Length > 0 ? string.Format(value, args) : value;
        }

        // 新增：获取本地化的星期名称数组
        public static string[] WeekNames
        {
            get
            {
                return new string[]
                {
                    GetString("Sunday"),
                    GetString("Monday"),
                    GetString("Tuesday"),
                    GetString("Wednesday"),
                    GetString("Thursday"),
                    GetString("Friday"),
                    GetString("Saturday")
                };
            }
        }


        public static void LoadLanguageResource(string resourcePath)
        {
            ResourceManager newRm = new ResourceManager(resourcePath, typeof(LanguageManager).Assembly);
            rm = newRm;
            translationCache.Clear();
            LanguageChanged?.Invoke(null, EventArgs.Empty);
        }

        // 新增：保存语言偏好
        private static void SaveLanguagePreference(string languageCode)
        {
            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings["PreferredLanguage"] == null)
                {
                    settings.Add("PreferredLanguage", languageCode);
                }
                else
                {
                    settings["PreferredLanguage"].Value = languageCode;
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException ex)
            {
                Console.WriteLine($"Error writing app settings: {ex.Message}");
                // 考虑记录错误或通知用户
            }
            catch (IOException ex)
            {
                Console.WriteLine($"Error accessing configuration file: {ex.Message}");
                // 考虑记录错误或通知用户
            }
        }

        // 新增：加载保存的语言设置
        private static void LoadSavedLanguage()
        {
            try
            {
                string savedLanguage = ConfigurationManager.AppSettings["PreferredLanguage"];
                if (!string.IsNullOrEmpty(savedLanguage))
                {
                    ChangeLanguage(savedLanguage);
                }
            }
            catch (ConfigurationErrorsException ex)
            {
                Console.WriteLine($"Error reading app settings: {ex.Message}");
                // 考虑记录错误或使用默认语言
            }
        }

        // 新增：获取当前语言代码
        public static string GetCurrentLanguage()
        {
            return currentCulture.Name;
        }

    }

    /// <summary>
    /// 窗口控件翻译
    /// </summary>
    public class MultiLanguageForm : AntdUI.Window
    {
        public MultiLanguageForm()
        {
            LanguageManager.LanguageChanged += OnLanguageChanged;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            UpdateUILanguage();
        }

        protected virtual void OnLanguageChanged(object sender, EventArgs e)
        {
            UpdateUILanguage();
        }

        protected virtual void UpdateUILanguage()
        {
            UpdateControlsText(this);
        }

        protected void UpdateControlsText(Control control)
        {
            UpdateControlProperties(control);

            foreach (Control childControl in control.Controls)
            {
                UpdateControlsText(childControl);
            }
        }



        protected void UpdateControlProperties(Control control)
        {
            string formName = this.Name;
            string controlName = control.Name;
            if (!string.IsNullOrEmpty(control.Name))
            {
                // 更新 Text 属性
                UpdateProperty(control, "Text", formName, controlName, "_Text");
                if (control is NaviButton2 naviButton)
                {
                    UpdateControlText(control, formName);
                }
                else if (control is TButton tButton)
                {
                    UpdateControlText(control, formName);
                }


                // 处理特定类型的控件
                else if (control is AntdUI.Button antdButton)
                {
                    UpdateProperty(antdButton, "Text", formName, controlName, "_Text");
                }
                else if (control is AntdUI.Label label)
                {
                    UpdateProperty(label, "Text", formName, controlName, "_Text");
                }
                else if (control is AntdUI.Input antdInput)
                {
                    UpdateProperty(antdInput, "PlaceholderText", formName, controlName, "_Placeholder");
                }
                else if (control is AntdUI.Steps steps)
                {
                    UpdateStepsTitle(steps, formName, controlName);
                }
                else if (control is StatusStrip status)
                {
                    UpdateStatusStripItems(status, formName);
                }
                else if (control is AntdUI.PageHeader antdWindowBar)
                {
                    UpdateProperty(antdWindowBar, "Text", formName, controlName, "_Text");
                }
                else if (control is AntdUI.Table antdTable)
                {
                    UpdateTableColumns(antdTable, formName, controlName);
                }

                else if (control is TitleTime titleTime)
                {
                    UpdateProperty(titleTime, "TitleName", formName, controlName, "_TitleName");
                }
                else if (control is Title title)
                {
                    UpdateProperty(title, "TitleName", formName, controlName, "_TitleName");
                }
                else if (control is LongTitleStyle2 longTitleStyle)
                {
                    UpdateProperty(longTitleStyle, "TitleName", formName, controlName, "_TitleName");
                }

                if (control is DataGridView dgv)
                {
                    UpdateDataGridViewLanguage(dgv, formName);
                }

                if (control is ListView listView)
                {
                    UpdateListViewLanguage(listView, formName);
                }

                if (control is UCElectricityMeterV) // 假设 EyMaterH1 是您自定义控件的类型
                {
                    LocalizeCustomControl(control, formName);
                }
                // 可以在这里添加更多特定控件类型的处理

                // 更新控件的 ToolTipText 属性
                //else if (control is SidebarNavigation antdSidebarNavigation)
                //{
                //    UpdateSidebarNavigationItems(antdSidebarNavigation, formName);
                //}

                //else if (control is CustomComboBox antdCustomComboBox)
                //{
                //    UpdateProperty(antdCustomComboBox, "WatermarkText", formName, controlName, "_WatermarkText");
                //}

                //else if (control is CustomGroupBox antdCustomGroupBox)
                //{
                //    UpdateProperty(antdCustomGroupBox, "Text", formName, controlName, "_Text");
                //}
                // 添加 CustomDataGridView 的处理
                //else if (control is CustomDataGridView dataGridView)
                //{
                //    UpdateDataGridViewColumns(dataGridView, formName, controlName);
                //}
            }
        }


        protected void UpdateControlText(Control control, string formName)
        {
            string baseResourceKey = $"{formName}_{control.Name}";

            // 尝试更新 Text 属性
            //string textKey = $"{baseResourceKey}_Text";
            //string translatedText = LanguageManager.GetString(textKey);
            //if (translatedText != textKey) // 如果找到了翻译
            //{
            //    control.Text = translatedText;
            //}

            // 尝试更新 TitleName 属性
            string titleNameKey = $"{baseResourceKey}_TitleName";
            string translatedTitleName = LanguageManager.GetString(titleNameKey);
            if (translatedTitleName != titleNameKey) // 如果找到了翻译
            {

                //control.Text = translatedText;
                var titleNameProperty = control.GetType().GetProperty("TitleName");
                if (titleNameProperty != null && titleNameProperty.CanWrite)
                {
                    titleNameProperty.SetValue(control, translatedTitleName);
                }
            }
        }


        /// <summary>
        /// Winform 默认DataGridView控件
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="formName"></param>
        protected void UpdateDataGridViewLanguage(DataGridView dgv, string formName)
        {
            foreach (DataGridViewColumn column in dgv.Columns)
            {
                if (!string.IsNullOrEmpty(column.Name))
                {
                    string resourceKey = $"{formName}_{dgv.Name}_{column.Name}Header";
                    string translatedHeader = LanguageManager.GetString(resourceKey);
                    if (translatedHeader != resourceKey) // 如果找到了翻译
                    {
                        column.HeaderText = translatedHeader;
                    }
                }
            }
        }


        /// <summary>
        /// 电表控件
        /// </summary>
        /// <param name="control"></param>
        protected void LocalizeCustomControl(Control control, string formName)
        {
            Type controlType = control.GetType();
            PropertyInfo[] properties = controlType.GetProperties();

            if (formName == "FrmMonitor")
            {
                foreach (PropertyInfo property in properties)
                {
                    if (property.PropertyType == typeof(string) && property.Name.StartsWith("Text"))
                    {
                        string propertyName = property.Name;
                        string key = $"{formName}_{control.Name}_{propertyName}";
                        string localizedText = LanguageManager.GetString(key);

                        if (!string.IsNullOrEmpty(localizedText))
                        {
                            property.SetValue(control, localizedText);
                        }
                    }
                }
            }
        }

        protected void UpdateListViewLanguage(ListView listView, string formName)
        {
            //foreach (ColumnHeader column in listView.Columns)
            //{
            //    string key = $"{formName}_{listView.Name}_{column.Name}_Text";
            //    string localizedText = LanguageManager.GetString(key);
            //    if (!string.IsNullOrEmpty(localizedText))
            //    {
            //        column.Text = localizedText;
            //    }
            //}
            if (formName != "FrmMain")
            {
                for (int i = 0; i < listView.Columns.Count; i++)
                {
                    string key = $"{formName}_{listView.Name}_Column{i}_Text";
                    string localizedText = LanguageManager.GetString(key);
                    if (!string.IsNullOrEmpty(localizedText))
                    {
                        listView.Columns[i].Text = localizedText;
                    }
                }
            }
        }


        /// <summary>
        /// 更新 DataGridView 的列标题
        /// </summary>
        private void UpdateDataGridViewColumns(CustomDataGridView dataGridView, string formName, string controlName)
        {
            try
            {
                foreach (DataGridViewColumn column in dataGridView.Columns)
                {
                    // 构建语言键：窗体名_控件名_Column_列名
                    //CommunicationEditForm_groupTable_Column_PlcNum
                    string languageKey = $"{formName}_{controlName}_Column_{column.Name}";

                    // 获取翻译后的列标题
                    string translatedHeader = LanguageManager.GetString(languageKey);

                    // 如果找到翻译，则更新列标题
                    if (!string.IsNullOrEmpty(translatedHeader) && translatedHeader != languageKey)
                    {
                        column.HeaderText = translatedHeader;
                    }
                }

                // 如果需要翻译行标题（RowHeaders）
                if (dataGridView.RowHeadersVisible)
                {
                    string rowHeaderKey = $"{formName}_{controlName}_RowHeader";
                    string translatedRowHeader = LanguageManager.GetString(rowHeaderKey);
                    if (!string.IsNullOrEmpty(translatedRowHeader) && translatedRowHeader != rowHeaderKey)
                    {
                        dataGridView.RowHeadersDefaultCellStyle.Format = translatedRowHeader;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error updating DataGridView columns: {ex.Message}");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="table"></param>
        /// <param name="formName"></param>
        /// <param name="controlName"></param>
        private void UpdateStepsTitle(AntdUI.Steps steps, string formName, string controlName)
        {
            if (steps.Items != null)
            {
                foreach (var item in steps.Items)
                {

                    ///格式  MainForm_mySteps_Item_Title = "姓名"  

                    string resourceKey = $"{formName}_{controlName}_{item.Name}_Title";
                    string translatedTitle = LanguageManager.GetString(resourceKey);
                    if (translatedTitle != resourceKey)
                    {
                        item.Title = translatedTitle;
                    }
                }
                // 强制表格重新加载布局以应用新的标题
                steps.Invalidate();
            }
        }



        /// <summary>
        /// Updates the text and tooltips of status strip items based on the current language settings.
        /// </summary>
        /// <param name="statusStrip">The status strip control to update</param>
        /// <param name="formName">The name of the form containing the status strip</param>
        public void UpdateStatusStripItems(StatusStrip statusStrip, string formName)
        {
            if (statusStrip == null || string.IsNullOrEmpty(formName))
                return;

            try
            {
                //FrmMain_StatusStrip_Status_Text = "就绪"
                //FrmMain_StatusStrip_Progress_Text = "进度"
                //FrmMain_StatusStrip_MenuButton_Text = "选项"
                //FrmMain_StatusStrip_MenuButton_Option1_Text = "选项1"
                //FrmMain_StatusStrip_MenuButton_Option2_Text = "选项2"

                foreach (ToolStripItem item in statusStrip.Items)
                {
                    UpdateStatusStripItem(item, formName);
                }

                // Force a redraw of the status strip
                statusStrip.Invalidate();
            }
            catch (Exception ex)
            {
                //Logger.LogError($"Error updating status strip: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// Updates text for a single status strip item
        /// </summary>
        private void UpdateStatusStripItem(ToolStripItem item, string formName)
        {
            if (item?.Name == null) return;

            // Update Text
            string textResourceKey = BuildResourceKey(formName, item.Name.ToString(), "Text");
            string translatedText = LanguageManager.GetString(textResourceKey);
            if (!string.Equals(translatedText, textResourceKey, StringComparison.Ordinal))
            {
                item.Text = translatedText;
            }

            // Handle nested items in dropdown buttons
            if (item is ToolStripDropDownButton dropDown)
            {
                UpdateDropDownItems(dropDown, formName);
            }
        }

        /// <summary>
        /// Updates text for dropdown items
        /// </summary>
        private void UpdateDropDownItems(ToolStripDropDownButton dropDown, string formName)
        {
            foreach (ToolStripItem dropDownItem in dropDown.DropDownItems)
            {
                if (dropDownItem?.Tag != null)
                {
                    string itemResourceKey = BuildResourceKey(formName,
                        $"{dropDown.Tag}_{dropDownItem.Tag}", "Text");
                    string translatedItemText = LanguageManager.GetString(itemResourceKey);

                    if (!string.Equals(translatedItemText, itemResourceKey,
                        StringComparison.Ordinal))
                    {
                        dropDownItem.Text = translatedItemText;
                    }
                }
            }
        }

        /// <summary>
        /// Builds the resource key for language lookup
        /// </summary>
        private string BuildResourceKey(string formName, string tag, string propertyName)
        {
            return $"{formName}_StatusStrip_{tag}_{propertyName}";
        }

        /// <summary>
        /// Table控件
        /// </summary>
        /// <param name="table"></param>
        /// <param name="formName"></param>
        /// <param name="controlName"></param>
        private void UpdateTableColumns(AntdUI.Table table, string formName, string controlName)
        {
            if (table.Columns != null)
            {
                foreach (var column in table.Columns)
                {

                    ///格式  MainForm_myTable_ColumnName_Title = "姓名"  

                    string resourceKey = $"{formName}_{controlName}_{column.Key}_Title";
                    string translatedTitle = LanguageManager.GetString(resourceKey);
                    if (translatedTitle != resourceKey)
                    {
                        column.Title = translatedTitle;
                    }
                }
                // 强制表格重新加载布局以应用新的标题
                table.LoadLayout();
            }
        }



        /// <summary>
        /// 侧边导航栏
        /// </summary>
        /// <param name="sidebarNavigation"></param>
        /// <param name="formName"></param>
        private void UpdateSidebarNavigationItems(SidebarNavigation sidebarNavigation, string formName)
        {
            foreach (var item in sidebarNavigation.GetItems())
            {
                //资源文件内部Key格式如下
                //FrmMain_SidebarItem_Home_Text = "Home"
                //FrmMain_SidebarItem_Statistics_Text = "Statistics"
                //FrmMain_SidebarItem_Search_Text = "Search"
                //FrmMain_SidebarItem_Recipe_Text = "Recipe"
                //FrmMain_SidebarItem_User_Text = "User"
                //FrmMain_SidebarItem_Settings_Text = "Settings"

                string resourceKey = $"{formName}_SidebarItem_{item.Tag}_Text";
                string translatedText = LanguageManager.GetString(resourceKey);
                if (translatedText != resourceKey)
                {
                    item.Text = translatedText;
                    sidebarNavigation.UpdateButtonText(item.Tag, translatedText);
                    // 查找对应的按钮并更新工具提示
                    var button = sidebarNavigation.Controls.OfType<AntdUI.Button>()
                        .FirstOrDefault(b => b.Tag == item);
                    if (button != null)
                    {
                        //sidebarNavigation.UpdateItemToolTip(button, translatedText);
                    }
                }
            }
            // 强制 SidebarNavigation 重新绘制以显示更新后的文本
            sidebarNavigation.Invalidate();
        }


        private void UpdateProperty(object control, string propertyName, string formName, string controlName, string suffix)
        {
            string resourceKey = $"{formName}_{controlName}{suffix}";
            string translatedValue = LanguageManager.GetString(resourceKey);
            if (translatedValue != resourceKey)
            {
                var property = control.GetType().GetProperty(propertyName);
                if (property != null && property.CanWrite)
                {
                    property.SetValue(control, translatedValue);
                }
            }
        }


        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                LanguageManager.LanguageChanged -= OnLanguageChanged;
            }
            base.Dispose(disposing);
        }
    }

    /// <summary>
    /// UserControl控件翻译
    /// </summary>
    public class MultiLanguageUserControl : UserControl
    {
        public MultiLanguageUserControl()
        {
            LanguageManager.LanguageChanged += OnLanguageChanged;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            UpdateUILanguage();
        }

        protected virtual void OnLanguageChanged(object sender, EventArgs e)
        {
            UpdateUILanguage();
        }

        protected virtual void UpdateUILanguage()
        {
            UpdateControlsText(this);
        }

        protected void UpdateControlsText(Control control)
        {
            UpdateControlProperties(control);

            foreach (Control childControl in control.Controls)
            {
                UpdateControlsText(childControl);
            }


        }

        protected void UpdateControlProperties(Control control)
        {
            string userControlName = this.Name;
            string controlName = control.Name;

            // 更新 Text 属性
            UpdateProperty(control, "Text", userControlName, controlName, "_Text");

            // 处理特定类型的控件
            if (control is AntdUI.Button antdButton)
            {
                UpdateProperty(antdButton, "Text", userControlName, controlName, "_Text");
            }
            else if (control is AntdUI.Label label)
            {

                UpdateProperty(label, "Text", userControlName, controlName, "_Text");
            }
            else if (control is AntdUI.Input antdInput)
            {
                UpdateProperty(antdInput, "PlaceholderText", userControlName, controlName, "_Placeholder");
            }

            else if (control is AntdUI.Tabs antdtabs)
            {
                UpdateTabsLanguage(antdtabs, userControlName);
            }
            else if (control is AntdUI.Table antdTable)
            {
                UpdateTableColumns(antdTable, userControlName, controlName);
            }

            else if (control is SidebarNavigation antdSidebarNavigation)
            {
                UpdateProperty(antdSidebarNavigation, "Text", userControlName, controlName, "_Text");
            }
            else if (control is CustomComboBox antdCustomComboBox)
            {
                UpdateProperty(antdCustomComboBox, "WatermarkText", userControlName, controlName, "_WatermarkText");
            }
            else if (control is CustomGroupBox antdCustomGroupBox)
            {
                UpdateProperty(antdCustomGroupBox, "Text", userControlName, controlName, "_Text");
            }

            // 添加 CustomDataGridView 的处理
            else if (control is CustomDataGridView dataGridView)
            {
                UpdateDataGridViewColumns(dataGridView, userControlName, controlName);
            }
            // 可以在这里添加更多特定控件类型的处理
        }


        /// <summary>
        /// 更新 DataGridView 的列标题
        /// </summary>
        private void UpdateDataGridViewColumns(CustomDataGridView dataGridView, string userControlName, string controlName)
        {
            try
            {
                foreach (DataGridViewColumn column in dataGridView.Columns)
                {
                    // 构建语言键：窗体名_控件名_Column_列名
                    string languageKey = $"{userControlName}_{controlName}_Column_{column.Name}";

                    // 获取翻译后的列标题
                    string translatedHeader = LanguageManager.GetString(languageKey);

                    // 如果找到翻译，则更新列标题
                    if (!string.IsNullOrEmpty(translatedHeader) && translatedHeader != languageKey)
                    {
                        column.HeaderText = translatedHeader;
                    }
                }

                // 如果需要翻译行标题（RowHeaders）
                if (dataGridView.RowHeadersVisible)
                {
                    string rowHeaderKey = $"{userControlName}_{controlName}_RowHeader";
                    string translatedRowHeader = LanguageManager.GetString(rowHeaderKey);
                    if (!string.IsNullOrEmpty(translatedRowHeader) && translatedRowHeader != rowHeaderKey)
                    {
                        dataGridView.RowHeadersDefaultCellStyle.Format = translatedRowHeader;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error updating DataGridView columns: {ex.Message}");
            }
        }

        /// <summary>
        /// Table控件
        /// </summary>
        /// <param name="table"></param>
        /// <param name="formName"></param>
        /// <param name="controlName"></param>
        private void UpdateTableColumns(AntdUI.Table table, string formName, string controlName)
        {
            if (table.Columns != null)
            {
                foreach (var column in table.Columns)
                {

                    ///格式  MainForm_myTable_ColumnName_Title = "姓名"  

                    string resourceKey = $"{formName}_{controlName}_{column.Key}_Title";
                    string translatedTitle = LanguageManager.GetString(resourceKey);
                    if (translatedTitle != resourceKey)
                    {
                        column.Title = translatedTitle;
                    }
                }
                // 强制表格重新加载布局以应用新的标题
                table.LoadLayout();
            }
        }


        /// <summary>
        /// 遍历Tabs中所有TabPage的所有控件
        /// </summary>
        /// <param name="tabs">要遍历的Tabs控件</param>
        /// <param name="action">对每个控件执行的操作</param>
        public static void ForEachControl(AntdUI.Tabs tabs, Action<Control> action)
        {
            if (tabs?.Pages == null) return;

            foreach (AntdUI.TabPage page in tabs.Pages)
            {
                // 遍历当前页面的所有控件
                ForEachControlRecursive(page, action);
            }
        }

        /// <summary>
        /// 遍历指定TabPage中的所有控件(包括子控件)
        /// </summary>
        /// <param name="page">要遍历的TabPage</param>
        /// <param name="action">对每个控件执行的操作</param>
        public static void ForEachControl(AntdUI.TabPage page, Action<Control> action)
        {
            ForEachControlRecursive(page, action);
        }

        /// <summary>
        /// 递归遍历控件树
        /// </summary>
        private static void ForEachControlRecursive(Control control, Action<Control> action)
        {
            // 执行操作
            action(control);

            // 递归遍历子控件
            foreach (Control child in control.Controls)
            {
                ForEachControlRecursive(child, action);
            }
        }



        #region tabs
        /// <summary>
        /// 为Tabs控件及其所有子控件更新语言
        /// </summary>
        /// <param name="tabs">要更新的Tabs控件</param>
        /// <param name="formName">窗体名称</param>
        public static void UpdateLanguage(Tabs tabs, string formName)
        {
            if (tabs?.Pages == null) return;

            foreach (AntdUI.TabPage page in tabs.Pages)
            {
                // 更新TabPage标题
                UpdateControlLanguage(page, formName, tabs.Name, page.Name, "_Text");

                // 递归更新所有子控件
                UpdateControlsLanguageRecursive(page.Controls, formName, tabs.Name, page.Name);
            }
        }

        /// <summary>
        /// 递归更新控件树中所有控件的语言
        /// </summary>
        private static void UpdateControlsLanguageRecursive(Control.ControlCollection controls, string formName, string tabsName, string pageName)
        {
            foreach (Control control in controls)
            {
                // 更新当前控件的文本
                UpdateControlLanguage(control, formName, tabsName, pageName, "_Text");

                // 针对特定类型控件的特殊处理
                if (control is DataGridView grid)
                {
                    UpdateDataGridViewLanguage(grid, formName, tabsName, pageName);
                }
                else if (control is AntdUI.Input input)
                {
                    UpdateInPutLanguage(input, formName, tabsName, pageName);
                }
                else if (control is CustomComboBox combo)
                {
                    UpdateComboBoxLanguage(combo, formName, tabsName, pageName);
                }
                else if (control is AntdUI.Table antdTable)
                {
                    UpdateTableLanguage(antdTable, formName, tabsName, pageName);
                }
                // 可以添加其他特殊控件的处理...

                // 递归处理子控件
                if (control.Controls.Count > 0)
                {
                    UpdateControlsLanguageRecursive(control.Controls, formName, tabsName, pageName);
                }
            }
        }

        /// <summary>
        /// 更新单个控件的语言
        /// </summary>
        private static void UpdateControlLanguage(Control control, string formName, string tabsName, string pageName, string suffix)
        {
            // 格式: FormName_TabsName_PageName_ControlName_Suffix  {pageName}_  {tabsName}_
            string resourceKey = $"{formName}_{tabsName}_{control.Name}{suffix}";
            string translatedText = LanguageManager.GetString(resourceKey);

            // 只在资源存在时更新
            if (translatedText != resourceKey)
            {
                control.Text = translatedText;
            }
        }

        private static void UpdateInPutLanguage(AntdUI.Input input, string formName, string tabsName, string pageName)
        {
            // 格式: FormName_TabsName_PageName_GridName_ColumnName_Title  {pageName}
            string resourceKey = $"{formName}_{tabsName}_{input.Name}_Placeholder";
            string translatedTitle = LanguageManager.GetString(resourceKey);

            if (translatedTitle != resourceKey)
            {
                input.PlaceholderText = translatedTitle;
            }
        }

        /// <summary>
        /// 更新DataGridView的列标题语言
        /// </summary>
        private static void UpdateDataGridViewLanguage(DataGridView grid, string formName, string tabsName, string pageName)
        {

            foreach (DataGridViewColumn column in grid.Columns)
            {
                // 格式: FormName_TabsName_PageName_GridName_ColumnName_Title  {pageName}
                string resourceKey = $"{formName}_{tabsName}_{grid.Name}_{column.Name}_Title";
                string translatedTitle = LanguageManager.GetString(resourceKey);

                if (translatedTitle != resourceKey)
                {
                    column.HeaderText = translatedTitle;
                }
            }
        }

        private static void UpdateTableLanguage(AntdUI.Table table, string formName, string tabsName, string pageName)
        {
            foreach (var column in table.Columns)
            {
                // 格式: FormName_TabsName_PageName_GridName_ColumnName_Title  {pageName} 
                //SettingControl_tabsSystemSet_configTable_PlcNum_Title
                string resourceKey = $"{formName}_{tabsName}_{table.Name}_{column.Key}_Title";
                string translatedTitle = LanguageManager.GetString(resourceKey);

                if (translatedTitle != resourceKey)
                {
                    column.Title = translatedTitle;
                }
            }
        }

        /// <summary>
        /// 更新ComboBox的项目语言
        /// </summary>
        private static void UpdateComboBoxLanguage(CustomComboBox combo, string formName, string tabsName, string pageName)
        {
            // 如果ComboBox是数据绑定的，可能需要特殊处理
            for (int i = 0; i < combo.Items.Count; i++)
            {
                //{pageName}_
                string resourceKey = $"{formName}_{tabsName}_{combo.Name}_WatermarkText";
                string translatedItem = LanguageManager.GetString(resourceKey);

                if (translatedItem != resourceKey)
                {
                    combo.WatermarkText = translatedItem;
                }
            }
        }

        /// <summary>
        /// 获取控件的完整资源键
        /// </summary>
        public static string GetResourceKey(Control control, string formName, string tabsName, string pageName, string suffix)
        {
            return $"{formName}_{tabsName}_{pageName}_{control.Name}{suffix}";
        }


        /// <summary>
        /// 更新Tabs及其所有子控件的语言
        /// </summary>
        /// <param name="tabs">Tabs控件</param>
        /// <param name="formName">窗体名称</param>
        public static void UpdateTabsLanguage(Tabs tabs, string formName)
        {
            if (tabs?.Pages == null) return;

            string tabsName = tabs.Name;
            foreach (Control control in GetAllControls(tabs))
            {
                // 构建资源键基础部分
                string baseKey = $"{formName}_{tabsName}_{control.Name}";
                string text;

                // 根据控件类型更新对应的文本属性
                switch (control)
                {
                    case AntdUI.Input input:
                        text = LanguageManager.GetString($"{baseKey}_Placeholder");
                        if (text != null) input.PlaceholderText = text;
                        break;

                    case CustomComboBox combo:
                        text = LanguageManager.GetString($"{baseKey}_WatermarkText");
                        if (text != null) combo.WatermarkText = text;
                        break;

                    case DataGridView grid:
                        foreach (DataGridViewColumn column in grid.Columns)
                        {
                            text = LanguageManager.GetString($"{baseKey}_{column.Name}_Title");
                            if (text != null) column.HeaderText = text;
                        }
                        break;

                    case AntdUI.Table table:
                        foreach (var column in table.Columns)
                        {
                            text = LanguageManager.GetString($"{baseKey}_{column.Key}_Title");
                            if (text != null) column.Title = text;
                        }
                        break;

                    default:
                        // 普通控件处理Text属性
                        text = LanguageManager.GetString($"{baseKey}_Text");
                        if (text != null) control.Text = text;
                        break;
                }
            }
        }

        /// <summary>
        /// 获取控件及其所有子控件
        /// </summary>
        private static IEnumerable<Control> GetAllControls(Tabs tabs)
        {
            var controls = new List<Control>();
            foreach (AntdUI.TabPage page in tabs.Pages)
            {
                controls.Add(page); // 添加TabPage本身
                controls.AddRange(GetChildControls(page));
            }
            return controls;
        }

        /// <summary>
        /// 递归获取子控件
        /// </summary>
        private static IEnumerable<Control> GetChildControls(Control control)
        {
            var controls = new List<Control>();
            foreach (Control child in control.Controls)
            {
                controls.Add(child);
                controls.AddRange(GetChildControls(child));
            }
            return controls;
        }
        #endregion



        private void UpdateProperty(object control, string propertyName, string userControlName, string controlName, string suffix)
        {
            string resourceKey = $"{userControlName}_{controlName}{suffix}";
            string translatedValue = LanguageManager.GetString(resourceKey);
            if (translatedValue != resourceKey)
            {
                var property = control.GetType().GetProperty(propertyName);
                if (property != null && property.CanWrite)
                {
                    property.SetValue(control, translatedValue);
                }
            }
        }


        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                LanguageManager.LanguageChanged -= OnLanguageChanged;
            }
            base.Dispose(disposing);
        }
    }

    public static class StringExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Translated(this string key)
        {
            return LanguageManager.GetString(key);
        }

        public static string Translated(this string key, params object[] args)
        {
            string translatedString = LanguageManager.GetString(key);
            return args.Length > 0 ? string.Format(translatedString, args) : translatedString;
        }
    }
}